import axios from 'axios'


import _config from '../../config/config'


/**
 * 处理 boolean 数据
 * @param data
 * @returns {*}
 */
function dealBooleanData(data) {
  // 遍历数据
  for (let key in data) {
    // console.log('key : ', key);
    // console.log('value : ', data[key]);
    if (data[key] === true) {
      data[key] = 'true'
    }
    if (data[key] === false) {
      data[key] = 'false'
    }
  }
  // console.log('data : ', data)
  return data
}


const axiosInstance = axios.create({
  baseURL: _config.basedir,
  timeout: 10000,
  // headers: {'X-Custom-Header': 'foobar'}
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 拦截器 拦截请求数据
axiosInstance.interceptors.request.use(
  (config) => {
    config.headers['Authorization'] = window.sessionStorage.getItem('token')
    return config
  },
  (err) => {
    console.log('拦截请求错误')
    console.log(err)
  }
)

// 拦截器  拦截响应数据
axiosInstance.interceptors.response.use((response) => {
  if (response && response.data) {
    if (response.data.success === 'true') {
      response.data.success = true
    } else if (response.data.success === 'false') {
      response.data.success = false
    }
    console.log(response.data)
    return response.data
  } else {
    console.log('-----------------axios数据拦截器拦截下来了-----data---start--------------')
    console.log(response)
    console.log('-----------------axios数据拦截器拦截下来了-----data----end----------------')
    return response
  }
}, function (error) {
  // if (error.response.status == 302 || error.response.status == 'UNKNOWN') {
  //   // alert("passport登录超时，刷新重新登录");
  //   window.location.reload()
  // } else {
  //   return Promise.reject(error)
  // }
  console.log('-----------------axios数据拦截器拦截下来了---rejected----start--------------')
  console.log(error)
  console.log('-----------------axios数据拦截器拦截下来了----rejected----end----------------')
})

export const _get = (path) => {
  return axiosInstance.get(path)
}

export const _put = (path, data) => {
  return axiosInstance.put(path, data)
}

export const _post = (path, data) => {
  console.log("post 传参 data : ", data)
  // 处理数据
  data = dealBooleanData(data)
  return axiosInstance.post(path, data)
}

export const _delete = (path) => {
  return axiosInstance.delete(path)
}
